import { Component, OnInit } from '@angular/core';
import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx';
import { NavController } from '@ionic/angular';
import { Router,NavigationExtras } from '@angular/router';
import { HttpClient } from "@angular/common/http";
import { AuthTokenService } from '@services/auth-token.service';
import { AlertController } from '@ionic/angular';
import {MatSnackBar} from '@angular/material';
import { CommonResponse,VerificationType,ToastColor,CommonService } from '@services/common-service.service';
@Component({
  selector: 'app-scan',
  templateUrl: './scan.page.html',
  styleUrls: ['./scan.page.scss'],
})
export class ScanPage implements OnInit {
  light: boolean;//判断闪光灯
  frontCamera: boolean;//判断摄像头
  isShow: boolean = false;//控制显示背景，避免切换页面卡顿
  appUserId = this.authTokenService.getAppUserId();
  deviceId = this.authTokenService.getDeviceId();
  constructor(private qrScanner: QRScanner, 
    public navController: NavController,
    private router:Router,
    private http: HttpClient,
    private alert:AlertController,
    private authTokenService: AuthTokenService,
    private commonService:CommonService,
    private snackBar:MatSnackBar
  ) { }

  ngOnInit() {
  }

  ionViewWillEnter() {
    // this.forwardToCheckout();
    this.qrScanner.prepare()
      .then((status: QRScannerStatus) => {
        if (status.authorized) {
          console.log('start scanning');
          // start scanning
          let scanSub = this.qrScanner.scan().subscribe((text: string) => {
            console.log('Scanned something', text);
            // alert(text);
            this.qrScanner.hide(); // hide camera preview
            scanSub.unsubscribe(); // stop scanning
        
            let requestData = JSON.parse(text);
            requestData.appUserId = this.appUserId;
            requestData.deviceId = this.deviceId;
            requestData.txnForm.invoiceList = JSON.stringify(requestData.invoicesForm);
            let url = "/scm/app/qrCodeCheck.do";
            this.http.post(url, requestData).subscribe((response: any) => {
              let body = response.responseBody;
              if(body.checkSuccess){
                this.qrScanner.hide(); // hide camera preview
                scanSub.unsubscribe(); // stop scanning
                // this.navController.back();
                requestData.txnForm.qrCodeId = body.qrCodeId;
                this.toCheckOut(requestData.txnForm);
              }else{
                // this.snackBar.open(body.checkMessage, "", {
                //   duration: 2000,
                // });
                // this.commonService.commonToast(ToastColor.warning,body.checkMessage);
                // this.alert.create({
                //   cssClass: 'my-custom-class',
                //   header: 'Alert',
                //   subHeader: 'Subtitle',
                //   message: body.checkMessage,
                //   buttons: ['OK']
                // });
                alert(body.checkMessage);
              }
            },(response)=>{
              let errorMsg = response.error.errorMsg;
            //  this.toCheckOut(requestData.txnForm);
              alert(errorMsg);
            });

            // scanSub.unsubscribe(); // stop scanning
            // this.navController.back();
            // this.toCheckOut();
          });
          // 打开摄像头
          // this.qrScanner.show();
        } else if (status.denied) {
          console.log('没有摄像头权限，请前往设置中开启');
        } else {
          // permission was denied, but not permanently. You can ask for
          //  permission again at a later time.
          console.log('没有摄像头权限，请前往设置中开启');
        }
      })
      .catch((e: any) => console.log('Error is', e));
  }

  toCheckOut(data){
    let urlData:NavigationExtras = {
      queryParams:data
    }
    this.router.navigate(['/tabs/home/scan/checkout'],urlData);
  }

  forwardToCheckout(){
    let countDown = 2;
    var id = setInterval(() => {
      countDown--;
      if(countDown == 0){
        clearInterval(id);
        if(location.pathname == "/tabs/home/scan"){
          this.router.navigate(['/tabs/home/scan/checkout']);
        }
      }
    }, 1000);
  }

  ngAfterViewInit(){
    
  }

  routerBack(){
    this.navController.back();
  }

  /*页面可见后执行 */
  ionViewDidEnter() {
    this.isShow = true;//显示背景
  }
  /**
  * 闪光灯控制，默认关闭
  */
  toggleLight() {
    if (this.light) {
      this.qrScanner.disableLight();
    } else {
      this.qrScanner.enableLight();
    }
    this.light = !this.light;
  }

  /**
  * 前后摄像头互换
  */
  toggleCamera() {
    if (this.frontCamera) {
      this.qrScanner.useBackCamera();
    } else {
      this.qrScanner.useFrontCamera();
    }
    this.frontCamera = !this.frontCamera;
  }

  hideCamera() {
    this.qrScanner.hide();//需要关闭扫描，否则相机一直开着
    this.qrScanner.destroy();//关闭
  }
  
  ionViewWillLeave() {
    this.hideCamera();
  }
}
